import React, { Component } from 'react'
import SearchInput from './SearchInput/index'
import List from './List/index'
import { ProductList, PaginationType } from '../../models/types'
import { queryFakeList } from '@/servers/search'
interface Props {

}
interface ListState {
    /**
     *  id: n,
      title: n + obj.title,
      img: obj.imgs[0],
      tags: obj.tags,
      price: (Math.random() * 1000).toFixed(2),
      link: '',
     */
    data: ProductList[],
    pagination: PaginationType
}
/**
 * queryList 因为子组件都会用到，所以定义在父组件
 * pageNo 用于加载更多数据
 * pageSize 每页数据
 * searchKey 搜索关键字
 * totalPage 总页数
 */
export default class SearchPage extends Component<Props, ListState> {
    state: ListState = {
        data: [],
        pagination: {
            pageNo: 0,
            pageSize: 5,
            searchKey: '',
            totalPage: 0
        }
    }
    // 后端默认pageSize是10
    queryList = (query: PaginationType) => {
        // 使用箭头函数才能找到this， 否则this为空
        let pageNo = this.state.pagination.pageNo
        let pageSize = this.state.pagination.pageSize
        let searchKey = this.state.pagination.searchKey


        if (query) {
            if (query.pageNo !== undefined) {
                pageNo = query.pageNo
            }

            pageSize = query.pageSize || pageSize
            searchKey = query.searchKey
        }
        if (pageNo !== undefined && pageSize !== undefined) {
            queryFakeList({ pageNo, pageSize, searchKey }).then((data) => {
                const { list } = data
                this.saveData(list)
            })
        }
    }
    searchTarget = (value: string) => {
        this.setState({
            data: [],
            pagination: {
                searchKey: value
            }
        })
        this.queryList({ searchKey: value, pageNo: 0 })
    }
    /**
     * 
     * @param partialState 是从后端获取的数据，它的pagination里面有totalPage
     */
    saveData = (partialState: {
        data?: ProductList[],
        pagination: PaginationType
    }) => {

        // partialState.data可能不存在，做兼容处理
        let mergeData = [...this.state.data, ...(partialState.data || [])]
        let mergePagination = { ...this.state.pagination, ...partialState.pagination }
        // 重新搜索
        if (mergePagination.pageNo === 0) {
            mergeData = partialState.data || []
        }
        this.setState({ data: mergeData, pagination: mergePagination })
    }
    render() {
        const { data, pagination } = this.state

        return (
            <div>
                <SearchInput queryList={this.queryList} searchTarget={this.searchTarget}></SearchInput>
                <List data={data} pagination={this.state.pagination} queryList={this.queryList}></List>
            </div>
        )
    }
}

